package com.tcc.mynote;

/* 第三个页面   主要实现一些安排  */

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.tcc.courseandplan.Plan;
import com.tcc.datebase.MyDB;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Fragment3 extends Fragment {

    private View view;
    private View layout;
    private ListView planList;
    private TextView remindContent;
    private Button addPlan;
    private int count;
    private RadioButton rb_remind_open;
    private RadioButton rb_remind_close;
    private CheckBox cb_remind_vibrato;
    private CheckBox cb_remind_ring;
    private DatePicker planDatePicker;
    private TimePicker planTimePicker;

    private int mYear = 2014;
    private int mMonth = 0;
    private int mDay = 1;
    private int mHour = 0;
    private int mMinute = 0;

    private boolean is_plan_remind;

    Date date = new Date();
    Calendar calendar = Calendar.getInstance();

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.tab_3, null);

        planList = (ListView) view.findViewById(R.id.planlist);
        planList.setVisibility(ListView.VISIBLE);

        remindContent = (TextView) view.findViewById(R.id.remindcontent);
        addPlan = (Button) view.findViewById(R.id.addplan);
        addPlan.setOnClickListener(new MyButtonListener());

        initPlan();

        return view;
    }

    public void initPlan() {
        ArrayList<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> item = new HashMap<String, Object>();
        Cursor c = new MyDB(this.getActivity()).queryAllPlans();
        count = c.getCount();
        int i = 0;
        int pnos[] = new int[count];
        String content = null;
        String remindTime = null;
        String isRemind = null;
        String isRemindByVibrato = null;
        String isRemindByRing = null;
        if (c.getCount() > 0) {
            while (c.moveToNext()) {
                pnos[i] = c.getInt(c.getColumnIndex("pno"));
                content = c.getString(c.getColumnIndex("content"));
                remindTime = c.getString(c.getColumnIndex("remindTime"));
                isRemind = c.getString(c.getColumnIndex("isRemind"));
                isRemindByVibrato = c.getString(c.getColumnIndex("isRemindByVibrato"));
                isRemindByRing = c.getString(c.getColumnIndex("isRemindByRing"));
                String remind = null;
                if (isRemind.equals("1") && isRemindByVibrato.equals("1") && isRemindByRing.equals("1")) {
                    remind = "提醒开启（" + remindTime + "）：震动+铃声";
                }
                if (isRemind.equals("1") && isRemindByVibrato.equals("1") && isRemindByRing.equals("0")) {
                    remind = "提醒开启（" + remindTime + "）：震动";
                }
                if (isRemind.equals("1") && isRemindByVibrato.equals("0") && isRemindByRing.equals("1")) {
                    remind = "提醒开启（" + remindTime + "）：铃声";
                }
                if (isRemind.equals("1") && isRemindByVibrato.equals("0") && isRemindByRing.equals("0")) {
                    remind = "提醒关闭（" + remindTime + "）";
                }
                if (isRemind.equals("0")) {
                    remind = "提醒关闭（" + remindTime + "）";
                }
                item = new HashMap<String, Object>();
                item.put("内容", content);
                item.put("细节", remind);
                listItem.add(item);
                i++;
            }
        }

        SimpleAdapter adapter = new SimpleAdapter(this.getActivity(), listItem,
                android.R.layout.simple_list_item_2, new String[]{"内容", "细节"},
                new int[]{android.R.id.text1, android.R.id.text2});

        planList.setAdapter(adapter);
        planList.setVisibility(ListView.VISIBLE);
        planList.setOnItemClickListener(new PlanOnItemClickListener(pnos));

        c.close();
    }

    // 计划列表事件内部类
    class PlanOnItemClickListener implements OnItemClickListener {

        int[] pno;

        public PlanOnItemClickListener(int[] pno) {
            // TODO Auto-generated constructor stub
            this.pno = pno;
        }

        String infoItemp[] = {"编辑", "删除"};

        public void onItemClick(AdapterView<?> parent, View view, final int position,
                                long id) {
            // TODO Auto-generated method stub
            System.out.println("position:" + position);
            AlertDialog.Builder builder = new Builder(getActivity());
            builder.setTitle("操作菜单").setItems(infoItemp, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    switch (which) {
                        case 0:
                            openPlanDialog(pno[position]);
                            System.out.println("pno:" + pno[position] + "position:" + position);
                            break;
                        case 1:
                            new MyDB(getActivity()).deletePlan(pno[position]);

                            initPlan();
                            break;

                        default:
                            break;
                    }
                }
            }).setPositiveButton("取消", null).show();
        }
    }


    // 打开计划日期时间选择器的对话框
    public void openPlanDialog(final int pno) {

        // 获取外部布局文件的资源
        LayoutInflater inflater = getActivity().getLayoutInflater();
        layout = inflater.inflate(R.layout.plan, (ViewGroup) getActivity().findViewById(R.id.plantime));

        rb_remind_open = (RadioButton) layout.findViewById(R.id.rb_remind_open);
        rb_remind_close = (RadioButton) layout.findViewById(R.id.rb_remind_close);
        cb_remind_vibrato = (CheckBox) layout.findViewById(R.id.cb_remindbyvibrato);
        cb_remind_ring = (CheckBox) layout.findViewById(R.id.cb_remindbyring);

        is_plan_remind = true;
        rb_remind_open.setChecked(true);
        cb_remind_vibrato.setChecked(true);
        cb_remind_ring.setChecked(true);

        rb_remind_open.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                cb_remind_vibrato.setEnabled(true);
                cb_remind_vibrato.setChecked(true);
                cb_remind_ring.setEnabled(true);
                cb_remind_ring.setChecked(true);
                is_plan_remind = true;
            }
        });
        rb_remind_close.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                cb_remind_vibrato.setEnabled(false);
                cb_remind_vibrato.setChecked(false);
                cb_remind_ring.setEnabled(false);
                cb_remind_ring.setChecked(false);
                is_plan_remind = false;
            }
        });
        cb_remind_vibrato.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    cb_remind_vibrato.setChecked(true);
                    System.out.println("is_plan_remind_vibrato = true");
                } else {
                    cb_remind_vibrato.setChecked(false);
                    System.out.println("is_plan_remind_vibrato = false");
                }
            }
        });
        cb_remind_ring.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    cb_remind_ring.setChecked(true);
                    System.out.println("is_plan_remind_ring = true");
                } else {
                    cb_remind_ring.setChecked(false);
                    System.out.println("is_plan_remind_ring = false");
                }
            }
        });

        calendar.setTimeInMillis(System.currentTimeMillis());
        planDatePicker = (DatePicker) layout.findViewById(R.id.plandatepicker);
        planDatePicker.init(mYear, mMonth, mDay, new DatePicker.OnDateChangedListener() {

            // 当时间被修改时，执行的方法
            public void onDateChanged(DatePicker view, int year, int monthOfYear,
                                      int dayOfMonth) {
                calendar.set(Calendar.YEAR, year + 1900);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                mYear = calendar.getTime().getYear();
                mMonth = calendar.getTime().getMonth();
                mDay = calendar.getTime().getDate();
                System.out.println(mYear + "." + mMonth + "." + mDay);
            }
        });

        planTimePicker = (TimePicker) layout.findViewById(R.id.plantimepicker);
        planTimePicker.setIs24HourView(true);
        planTimePicker.setCurrentHour(mHour);
        planTimePicker.setCurrentMinute(mMinute);
        planTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                // TODO Auto-generated method stub
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
                mHour = calendar.getTime().getHours();
                mMinute = calendar.getTime().getMinutes();
            }
        });


        final MyDB db = new MyDB(this.getActivity());
        Cursor c = db.queryAllPlans();
        final int count = c.getCount();

        if (count == 5 && pno == 0) {
            Toast.makeText(this.getActivity(), "只能添加5个", Toast.LENGTH_SHORT).show();
        } else {
            new AlertDialog.Builder(this.getActivity()).setTitle(remindContent.getText().toString().trim()).setView(layout)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            if (rb_remind_open.isChecked() && !cb_remind_vibrato.isChecked() && !cb_remind_ring.isChecked()) {
                                Toast.makeText(getActivity(), "请选择提醒方式", Toast.LENGTH_LONG).show();
                            } else {

                                Calendar nowCalendar = Calendar.getInstance();
                                nowCalendar.setTimeInMillis(System.currentTimeMillis());
                                System.out.println(date.toString());
                                calendar.set(Calendar.YEAR, mYear);
                                calendar.set(Calendar.MONTH, mMonth);
                                calendar.set(Calendar.DAY_OF_MONTH, mDay);
                                System.out.println(planDatePicker.getYear() + "/" + (planDatePicker.getMonth() + 1) + "/" + (planDatePicker.getDayOfMonth()));
                                calendar.set(Calendar.HOUR_OF_DAY, mHour);
                                calendar.set(Calendar.MINUTE, mMinute);
                                calendar.set(Calendar.SECOND, 0);
                                calendar.set(Calendar.MILLISECOND, 0);
                                Base base = new Base();
                                String[] strsWeek = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
                                String remindTime = (calendar.getTime().getYear() + 1900) + "/" + (calendar.getTime().getMonth() + 1) + "/" + (calendar.getTime().getDate()) + " " + base.formateTime(calendar.getTime().getHours()) + ":" + base.formateTime(calendar.getTime().getMinutes()) + " " + strsWeek[calendar.getTime().getDay()];


                                Plan plan = new Plan(pno, remindContent.getText().toString().trim(), remindTime, is_plan_remind, cb_remind_vibrato.isChecked(), cb_remind_ring.isChecked());
                                System.out.println("pno:" + plan.getPno());
                                if (pno == 0) {
                                    // 添加pno不重复，而且在1-5之内的计划
                                    int planNo = 1;
                                    Cursor c1 = db.queryPlanByPno(1);
                                    Cursor c2 = db.queryPlanByPno(2);
                                    Cursor c3 = db.queryPlanByPno(3);
                                    Cursor c4 = db.queryPlanByPno(4);
                                    Cursor c5 = db.queryPlanByPno(5);

                                    if (c1.getCount() <= 0) {
                                        planNo = 1;
                                    } else if (c2.getCount() <= 0) {
                                        planNo = 2;
                                    } else if (c3.getCount() <= 0) {
                                        planNo = 3;
                                    } else if (c4.getCount() <= 0) {
                                        planNo = 4;
                                    } else if (c5.getCount() <= 0) {
                                        planNo = 5;
                                    }
                                    c1.close();
                                    c2.close();
                                    c3.close();
                                    c4.close();
                                    c5.close();

                                    plan.setPno(planNo);
                                    System.out.println("planNo:" + planNo);
                                    db.insertPlan(plan);// 添加计划提醒
                                } else {
                                    System.out.println("udpdate pno:" + pno);
                                    db.updatePlanByPno(pno, plan);// 更新计划提醒
                                }

                                initPlan();// 更新列表
                            }

                        }
                    })
                    .setNegativeButton("取消", null).show();
        }

        c.close();

    }

    class MyButtonListener implements OnClickListener {

        public void onClick(View v) {

            if (remindContent.getText().toString().trim().equals("")) {
                Toast.makeText(getActivity(), "请添加提醒内容", Toast.LENGTH_SHORT).show();
            } else {
                openPlanDialog(0);
            }
        }
    }
}
